package com.dolphin.config.shiro;

import com.dolphin.config.shiro.customToken.WxToken;
import com.dolphin.model.User;
import com.dolphin.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * Custom shiroRealm
 *
 * @author dolphin
 */
@Component
public class WxRealm extends AuthorizingRealm {
    private final static Logger LOGGER = LoggerFactory.getLogger(WxRealm.class);
    @Autowired
    private UserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) throws AuthenticationException {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        WxToken userToken = (WxToken) token;
        String account = userToken.getAccount();
        User user = userService.getUserByAccount(account);
        return new SimpleAuthenticationInfo(user, "", getName());
    }

    @Override
    public Class getAuthenticationTokenClass() {
        return WxToken.class;
    }

    /**
     * 自定义密码验证匹配器
     */
    @PostConstruct
    public void initCredentialsMatcher() {
        setCredentialsMatcher(new SimpleCredentialsMatcher() {
            @Override
            public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
                return true;
            }
        });
    }
}
